using System;
using System.Net.Sockets;
using chromium.Log;

namespace chromium.Proxy
{
    public sealed class HttpListener : Listener
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(HttpListener));

        public HttpListener(int port)
            : base(port)
        {
        }

        public override void OnAccept(IAsyncResult ar)
        {
            HttpClient client = null;
            try
            {
                Socket lSocket = (Socket)ar.AsyncState;

                Socket newSocket = lSocket.EndAccept(ar);

                if (newSocket != null)
                {
                    client = new HttpClient(newSocket);
                    client.ReceiveRequest(null);
                }
            }
            catch (Exception e)
            {
                if (client != null)
                    client.Dispose();

                logger.Error("Accept socket failed:", e);
            }
        }
    }
}